package com.mina.app;

import com.mina.entity.MinaMsg;
import com.mina.handler.MinaClientHandler;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * 客户端
 *
 * @author sam
 */
public class MinaClient {

    public static void main(String[] args) {
        // create a socket
        NioSocketConnector connector = new NioSocketConnector();
        DefaultIoFilterChainBuilder chainBuilder = connector.getFilterChain();

        // settings
        chainBuilder.addLast("objectFilter", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        connector.setHandler(new MinaClientHandler());
        connector.setConnectTimeoutMillis(10000);

        // connect to server
        ConnectFuture connectFuture = connector.connect(new InetSocketAddress("localhost", 9999));
        connectFuture.awaitUninterruptibly();
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入您的昵称：");
        while (true) {
            MinaMsg msg = new MinaMsg();
            String from = scanner.nextLine();
            String to = "mina";
            String type = "send";

            msg.setFrom(from);
            msg.setTo(to);
            msg.setType(type);
//            System.out.print(from + ":");
            msg.setInfo(scanner.nextLine());

            connectFuture.getSession().write(msg);
        }

    }

}
